<template>
  <el-form
    ref="formRef"
    :model="dynamicValidateForm"
    label-width="60px"
    class="demo-dynamic"
  >
    <el-form-item prop="webUrl" label="地址" :rules="data.formRules.webUrl">
      <el-input v-model="dynamicValidateForm.webUrl">
        <template #append>
          <el-button @click="getIcon">获取图标</el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="webName" label="名称" :rules="data.formRules.webName">
      <el-input v-model="dynamicValidateForm.webName"> </el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">Submit</el-button>
      <!-- <el-button @click="addDomain">New domain</el-button> -->
      <el-button @click="resetForm(formRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch, onBeforeUnmount } from 'vue'
import type { FormInstance } from 'element-plus'
const props = defineProps({
  formData: {
    type: Object,
    default: {},
  },
})
console.log('formMain组件', props.formData)

const emit = defineEmits(['submitEvent'])
const data = reactive({
  formRules: {
    webUrl: [
      {
        required: true,
        message: 'Please input email address',
        trigger: 'blur',
      },
    ],
    webName: {
      required: true,
      message: 'domain can not be null',
      trigger: 'blur',
    },
  },
  formData: computed(() => {
    return {
      id: props.formData.id,
      webUrl: props.formData.webUrl,
      webName: props.formData.webName,
    }
  }),
})

const formRef = ref<FormInstance>()
// 双向绑定的表单数据
const dynamicValidateForm = reactive({
  webName: data.formData.webName,
  webUrl: data.formData.webUrl,
})

// 两个按钮：提交和重置
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      const appInfo = {
        id: props.formData.id,
        webUrl: dynamicValidateForm.webUrl,
        webName: dynamicValidateForm.webName,
      }
      console.log('submit!', appInfo)
      emit('submitEvent', appInfo)
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 异步获取图标
const getIcon = () => {
  console.log('发送请求获取图标')
}

defineExpose({
  submitForm,
})
</script>
